package advance.x000.acw_95;


import java.util.Arrays;
import java.util.Scanner;


public class Main3 {
    public static int N = 6;
    public static int[] dx = {0, 1, 0, -1}; // N E S W
    public static int[] dy = {1, 0, -1, 0};// N E S W
    public static char[][] lamp = new char[N][N];
    public static char[][] back = new char[N][N];

    static void turn(int x, int y) {
        for (int i = 0; i < 5; i++) {
            int a = x + dx[i];
            int b = y + dy[i];
            if (a < 0 || a >= 5 || b < 0 || b >= 5) continue;
            lamp[a][b] ^= 1;
        }
    }

    //递归实现排列型枚举
    public static void main(String[] args) {
        Main3 solution = new Main3();
        Scanner scanner = new Scanner(System.in);
        // 5X5 组数
        int n = scanner.nextInt();
        while (n-- != 0) {
            for (int i = 0; i < 5; i++) {
                lamp[i] = scanner.next().toCharArray();
            }

            int res = 7;
            for (int op = 0; op < 32; op++) {
                for (int j = 0; j < 5; ++j) {
                    back[j] = Arrays.copyOf(lamp[j], 5);
                }

                int step = 0;
                for (int i = 0; i < 5; i++) {
                    if ((op >> i & 1) == 1) {
                        step++;
                        turn(0, i);
                    }
                }

                for (int i = 0; i < 4; i++) {
                    for (int j = 0; j < 5; j++) {
                        if (lamp[i][j] == '0') {
                            step++;
                            turn(i + 1, j);
                        }
                    }
                }

                boolean dark = false;
                for (int j = 0; j < 5; j++) {
                    if (lamp[4][j] == '0') {
                        dark = true;
                        break;
                    }
                }

                if (!dark) res = Math.min(res, step);

                for (int j = 0; j < 5; j++) {
                    lamp[j] = Arrays.copyOf(back[j], 5);
                }

            }

            if (res > 6) res = -1;
            System.out.println(res);

        }
    }


}
